package cl.pds.pruebacliente;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Iterator;

import org.json.JSONException;
import org.json.JSONObject;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import com.google.gson.JsonObject;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

public class Pestana2 extends Activity {
	
	private String URL = "http://172.22.204.151:8080/PDSPrueba1WS/services/Prueba1PdsORMWS";
		private String NAMESPACE = "http://ws.pds.prueba1";

	ArrayList<String> Pacientes;
	ArrayList<String> Prestaciones;
	Spinner pacientesSpinner;
	Spinner prestacionesSpinner;
	//DatePicker fechaEditText;
	Button botonFecha;
	EditText diagnosticoEditText;
	private int mYear; 
	private int mMonth; 
	private int mDay;
	static final int DATE_DIALOG_ID = 0;
	

	private DatePickerDialog.OnDateSetListener mDateSetListener = 
	new DatePickerDialog.OnDateSetListener() { 
	public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth){ 
	mYear = year; 
	mMonth = monthOfYear; 
	mDay = dayOfMonth; 
	updateDisplay(); 
	} 
	};

	private void updateDisplay() { 
	botonFecha.setText( 
	new StringBuilder() 
	// Month is 0 based so add 1 
	.append(mMonth + 1).append("-") 
	.append(mDay).append("-") 
	.append(mYear).append(" ")); 
	}
	@Override
	protected Dialog onCreateDialog(int id) { 
	switch (id) { 
	case DATE_DIALOG_ID: 
	return new DatePickerDialog(this, 
	mDateSetListener, 
	mYear, mMonth, mDay); 
	} 
	return null;
	}
	
	
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.pestana2);
		pacientesSpinner = (Spinner) findViewById(R.id.SpinnerPaciente);
		prestacionesSpinner = (Spinner) findViewById(R.id.SpinnerPrestaciones);
		//fechaEditText = (DatePicker) findViewById(R.id.PickerFecha);
		diagnosticoEditText = (EditText) findViewById(R.id.edTxtDiagnostico);
		botonFecha= (Button)findViewById(R.id.btnFecha);
		Pacientes = new ArrayList<String>();
		Prestaciones = new ArrayList<String>();
		new ObtenerPacientesPrestacionBackground().execute();
		// get the current date 
		final Calendar c = Calendar.getInstance(); 
		mYear = c.get(Calendar.YEAR); 
		mMonth = c.get(Calendar.MONTH); 
		mDay = c.get(Calendar.DAY_OF_MONTH); 
		// display the current date (this method is below) 
		updateDisplay();
	}
	
	public void ObtenerFecha(View v){
		showDialog(DATE_DIALOG_ID);
	}

	public void ingresar(View v){
		JsonObject jsonObjectAtencion = new JsonObject();
		
		jsonObjectAtencion.addProperty("Fecha",botonFecha.getText().toString());
		jsonObjectAtencion.addProperty("diagnostico", diagnosticoEditText.getText().toString());
		jsonObjectAtencion.addProperty("paciente_id", Pacientes.get(pacientesSpinner.getSelectedItemPosition()));
		jsonObjectAtencion.addProperty("prestacion_id", Prestaciones.get(prestacionesSpinner.getSelectedItemPosition()));
		new AddPeliculaBackground().execute(jsonObjectAtencion.toString());
	}

	class ObtenerPacientesPrestacionBackground extends AsyncTask<Void, Void, HashMap<String, String>>{
		
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
    		progressDialog = ProgressDialog.show(
    				Pestana2.this,
    				"Ingreso de Atencion", 
    				"Espere mientras se cargan las opciones...", 
    				true);
			super.onPreExecute();
		}
		
		@Override
		protected HashMap<String, String> doInBackground(Void... params) {

			HashMap<String, String> resultado = new HashMap<String, String>();
			String pacientesJSON="";
			String METHOD_NAME = "getPacientes";
			String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				pacientesJSON = resultString.toString();
				resultado.put("Contenido", pacientesJSON);

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			String prestacionesJSON="";
			METHOD_NAME = "getPrestaciones";
			SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			request = new SoapObject(NAMESPACE, METHOD_NAME);
			soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes =true;
			soapEnvelope.setOutputSoapObject(request);

			aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				prestacionesJSON = resultString.toString();
				resultado.put("Contenido", prestacionesJSON);

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return resultado;
		}

		@Override
		protected void onPostExecute(HashMap<String, String> result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			//Valido que tenga la informacion necesaria
			if(result.containsKey("Pacientes") && !"".equals(result.get("Pacientes"))){
				try {
					ArrayList<String> generosList = new ArrayList<String>();
					JSONObject pacienteResultado = new JSONObject(result.get("Pacientes"));
					String contenido = pacienteResultado.getString("Contenido");
					JSONObject AtencionesJSONArray = new JSONObject(contenido);
					AtencionesJSONArray.names();
					AtencionesJSONArray.keys();
					for (Iterator iterator = AtencionesJSONArray.keys(); iterator.hasNext();) {
						String string = (String) iterator.next();
						Pacientes.add(string);
						generosList.add(AtencionesJSONArray.getString(string));
						
					}
					
					ArrayAdapter<String> pacientesAdapter = new ArrayAdapter<String>(Pestana2.this, android.R.layout.simple_spinner_item, generosList);
					pacientesSpinner.setAdapter(pacientesAdapter);

				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


			}else{
				Toast.makeText(Pestana2.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}
			
			if(result.containsKey("Prestaciones") && !"".equals(result.get("Prestaciones"))){
				try {
					ArrayList<String> PrestacionesList = new ArrayList<String>();
					JSONObject prestacionResultado = new JSONObject(result.get("Prestaciones"));
					String contenido = prestacionResultado.getString("Contenido");
					JSONObject AtencionesJSONArray = new JSONObject(contenido);
					AtencionesJSONArray.names();
					AtencionesJSONArray.keys();
					for (Iterator iterator = AtencionesJSONArray.keys(); iterator.hasNext();) {
						String string = (String) iterator.next();
						Prestaciones.add(string);
						PrestacionesList.add(AtencionesJSONArray.getString(string));
						
					}
					
					ArrayAdapter<String> prestacionesAdapter = new ArrayAdapter<String>(Pestana2.this, android.R.layout.simple_spinner_item, PrestacionesList);
					prestacionesSpinner.setAdapter(prestacionesAdapter);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}


			}else{
				Toast.makeText(Pestana2.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}
		}
	}

	class AddPeliculaBackground extends AsyncTask<String, Void, String>{
		
		private ProgressDialog progressDialog;

		@Override
		protected void onPreExecute() {
    		progressDialog = ProgressDialog.show(
    				Pestana2.this,
    				"Ingreso de Atenciones", 
    				"Espere mientras se agrega el paciente...", 
    				true);
			super.onPreExecute();
		}
		
		@Override
		protected String doInBackground(String... params) {

			String resultado = new String();
			String METHOD_NAME = "addAtencion";
			String SOAP_ACTION = NAMESPACE +"/" +METHOD_NAME;
			SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
			SoapSerializationEnvelope soapEnvelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
			soapEnvelope.dotNet = true;
			soapEnvelope.implicitTypes = true;
			soapEnvelope.setOutputSoapObject(request);

			request.addProperty("AtencionJson", params[0]);

			HttpTransportSE aht = new HttpTransportSE(URL);

			try {
				aht.call(SOAP_ACTION, soapEnvelope);
				SoapPrimitive resultString = (SoapPrimitive)soapEnvelope.getResponse();
				resultado = resultString.toString();

			} catch (IOException e) {
				e.printStackTrace();
			} catch (XmlPullParserException e) {
				e.printStackTrace();
			}

			return resultado;
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			progressDialog.dismiss();
			//Valido que tenga la informacion necesaria
			if("1".equals(result)){
				Toast.makeText(Pestana2.this, "Ingresada correctamente", Toast.LENGTH_LONG).show();
			}else{
				Toast.makeText(Pestana2.this, "Error al obtener la informacion necesaria", Toast.LENGTH_LONG).show();
			}
		}
	}
	

}
